package com.strato.json.v1_0_0.core;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateTypeAdapter implements JsonSerializer<Date> , JsonDeserializer<Date>{

	private final static String patten = "yyyy-MM-dd HH:mm:ss";
	@Override
	public Date deserialize(JsonElement arg0, Type arg1,JsonDeserializationContext arg2) throws JsonParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(patten);
		try{
			Date date = sdf.parse(arg0.getAsString());
			return date;
		}catch(Exception e){
			throw new JsonParseException(e);
		}
	}

	@Override
	public JsonElement serialize(Date arg0, Type arg1,JsonSerializationContext arg2) {
		SimpleDateFormat sdf = new SimpleDateFormat(patten);
		String timeStr = sdf.format(arg0);
		return new JsonPrimitive(timeStr);
	}


}
